package com.ligq.vbasedemo.fragment

import android.app.Activity
import android.content.Context
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import com.ligq.vbasedemo.R
import com.ligq.vbasedemo.encode.H264SREncode

class ScreenRecordingFragment : BaseFragment() {
    private var projectionManager: MediaProjectionManager? = null
    private var mediaProjection: MediaProjection? = null
    override fun initView(view: View?) {
        view?.findViewById<Button>(R.id.btn_sr)?.setOnClickListener {
            start()
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_sr
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        projectionManager =
            context?.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager?
        val createScreenCaptureIntent = projectionManager?.createScreenCaptureIntent()
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
            if (activityResult.resultCode != Activity.RESULT_OK) {
                return@registerForActivityResult
            }
            mediaProjection =
                activityResult.data?.let { intent ->
                    projectionManager?.getMediaProjection(
                        activityResult.resultCode,
                        intent
                    )
                }
        }.launch(createScreenCaptureIntent)
    }

    private fun start() {
        if (mediaProjection != null) {
            val h264Encode = mediaProjection?.let { H264SREncode(it) }
            h264Encode?.start()
        } else {
            Toast.makeText(context, "录屏失败，请重试！！", Toast.LENGTH_SHORT).show()
        }
    }
}